package com.hqm.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.hqm.dao.TransactionDao;
import com.hqm.meta.Product;
import com.hqm.meta.Transaction;
import com.hqm.meta.User;

@Service
public class TransactionServiceImpl implements TransactionService {
	@Resource
	private TransactionDao transactionDao;

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public Boolean addtrx(Transaction transaction) {
		Boolean isAdd = true;
		try {
			transactionDao.addTrxRecord(transaction);
		} catch (DataAccessException e) {
			isAdd = false;
		}
		
		return isAdd;
	}

	@Override
	@Transactional(propagation = Propagation.SUPPORTS)
	public Integer getProductSoldNum(Product product) {
		return transactionDao.getProSoldCnts(product.getId());
	}

	@Override
	@Transactional(propagation = Propagation.SUPPORTS)
	public Integer getProductBuyNum(Product product, User buyer) {
		return transactionDao.getProBuyedCnts(product.getId(), buyer.getId());
	}

	@Override
	@Transactional(propagation = Propagation.SUPPORTS)
	public Boolean isSell(Product product) {
		Boolean isSold = false;
		Integer soldNum = transactionDao.getProSoldCnts(product.getId());
		if (soldNum > 0) {
			isSold = true;
		}
		
		return isSold;
	}

	@Override
	@Transactional(propagation = Propagation.SUPPORTS)
	public Boolean isBuy(Product product, User buyer) {
		Boolean isBuyed = false;
		Integer buyedNum = transactionDao.getProBuyedCnts(product.getId(), buyer.getId());
		if (buyedNum > 0) {
			isBuyed = true;
		}
		
		return isBuyed;
	}

	@Override
	@Transactional(propagation = Propagation.SUPPORTS)
	public List<Transaction> getTrx(Product product, User buyer) throws Exception{
		return transactionDao.getTransaction(product.getId(), buyer.getId());
	}

	@Override
	@Transactional(propagation = Propagation.SUPPORTS)
	public List<Transaction> getTrx(User buyer) throws Exception {
		return transactionDao.getTransactionForBuyer(buyer.getId());
	}

}
